package com.example.tse.rbyair.PKactivity;

import android.animation.Animator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ImageSpan;
import android.text.style.StrikethroughSpan;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tse.rbhttpservice.service.RemoteServiceFactory;
import com.example.tse.rbhttpservice.service.RemoteServiceListenerT;
import com.example.tse.rbhttpservice.service.common.model.CommonShareGoodsRequest;
import com.example.tse.rbhttpservice.service.common.model.CommonShareGoodsResponse;
import com.example.tse.rbhttpservice.service.goods.model.GoodsFavoriteRequest;
import com.example.tse.rbhttpservice.service.goods.model.GoodsFavoriteResponse;
import com.example.tse.rbhttpservice.service.goods.model.GoodsGetPriceResponse;
import com.example.tse.rbhttpservice.service.goods.model.GoodsGetRequest;
import com.example.tse.rbhttpservice.service.goods.model.GoodsGetResponse;
import com.example.tse.rbhttpservice.service.goods.model.GoodsGetSpecs;
import com.example.tse.rbhttpservice.service.goods.model.GoodsGetSpecsSpecValues;
import com.example.tse.rbhttpservice.service.home.model.HomeGetSecondBody;
import com.example.tse.rbhttpservice.service.home.model.HomeGetSeconds;
import com.example.tse.rbhttpservice.service.shopping.model.ShoppingAddRequest;
import com.example.tse.rbhttpservice.service.shopping.model.ShoppingAddResponse;
import com.example.tse.rbyair.MainActivity;
import com.example.tse.rbyair.R;
import com.example.tse.rbyair.base.RbBaseActivity;
import com.example.tse.rbyair.login.LoginActivity;
import com.example.tse.rbyair.util.AppInforUtil;
import com.example.tse.rbyair.util.RbImageLoader;
import com.example.tse.rbyair.util.SharedPreferenceUtils;
import com.example.tse.rbyair.widget.others.CustomDigitalClock;
import com.example.tse.rbyair.widget.others.MyParallaxScrollView;
import com.example.tse.rbyair.widget.others.ProductSpecificationPopwindow;
import com.example.tse.rbyair.widget.tagview.FlowLayout;

import org.kymjs.kjframe.log.L;
import org.kymjs.kjframe.utils.DensityUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;

/**
 * Created by hp on 16/1/26.
 */
public class ProductDetialActivity extends RbBaseActivity implements View.OnClickListener{
    private MyParallaxScrollView scrollview;
    private LinearLayout product_guige_lay ;
    private String productId;
    private String type;
    private String relativeId;
    private String secondId;
    private String deviceId;
    private String isFastBuy;
    private String isMiaosha;
    private String rudder_position;
    private String rudder_route;

    private TextView product_name;  //商品名称
    private TextView product_price;  // 商品价格
    private TextView product_mktprice;  // 市场价
    private TextView product_totalsaved;  // 节省多少钱
    private TextView product_wight;  //重量
    private TextView product_brand;
    private TextView product_sort;
    private TextView product_number;
    private TextView product_guigetxt;  //所选规格
    private ImageView product_save ;  //收藏
    private ImageView product_share; // 分享

    private TextView product_addtoshoppingcart ; //普通商品 加入购物车
    private TextView product_buynow;   //普通商品立即购买
    private TextView product_fast_buynow ; //秒杀商品立即购买

    private TextView product_empty;   //商品下架
    private LinearLayout product_bottom_lay;  //最下面操作栏

    private TextView product_timetxt;   //倒计时后面文字
    private CustomDigitalClock product_timerview ; //倒计时
    private LinearLayout product_timerlay;   //倒计时布局
    private TextView product_endtag ; // 倒计时结束标志

    private WebView web;
    private ProductSpecificationPopwindow popwindow;
    private PopupWindow pop;
    private Platform.ShareParams shareParams;
    private Object secondsMode;
    private HomeGetSeconds secondsMode1;
    private HomeGetSecondBody secondsMode2;
    private GoodsGetResponse tt;
    private Dialog dialog;

    private int savedTag = 0;
    private int b = 0;
    private int pluslayCount = 1;
    private String goodsId = "";
    private String notice = "0";
    private String isFirstOne = "";
    private long timeGap = 0;
    private boolean isAniting = false;
    private boolean isBuyNow = false;
    private boolean isAdd2Shopcart = false;
    private boolean isMultiTag = false;
    private Animation animation2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.productdetial);
        productId = getIntent().getStringExtra("productId");
        type = getIntent().getStringExtra("type");
        relativeId = getIntent().getStringExtra("relativeId");
        secondId = getIntent().getStringExtra("secondId");   //秒杀
        deviceId = getIntent().getStringExtra("deviceId");   //
        isFastBuy = getIntent().getStringExtra("isFastBuy");
        isMiaosha = getIntent().getStringExtra("开抢");
        timeGap = getIntent().getLongExtra("timeGap", 0);
        notice = getIntent().getStringExtra("notice");
        isFirstOne = getIntent().getStringExtra("isFirstOne");
        //		secondsMode = (HomeGetSeconds) getIntent().getParcelableExtra("secondsMode");

        secondsMode =  getIntent().getSerializableExtra("secondsMode");
        if(secondsMode instanceof HomeGetSeconds){           //
            secondsMode1 = (HomeGetSeconds) secondsMode;
        }else if(secondsMode instanceof HomeGetSecondBody){
            secondsMode2 = (HomeGetSecondBody) secondsMode;
        }

        rudder_position  = getIntent().getStringExtra("rudder_position");
        rudder_route  = getIntent().getStringExtra("rudder_route");

        if(isFastBuy == null)
            isFastBuy = "0";
        if(type == null)
            type = "0";

        animation2 = AnimationUtils.loadAnimation(this, R.anim.cart_anim2);
        animation2.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                reclassify_addcartiv.setVisibility(View.INVISIBLE);
            }
        });

        initViews();
    }

    private void initViews(){
        setTitleTxt(R.string.product_detail);
        setRightImageResouse(R.drawable.share_index);
        hidePoint();

        showShopCart();
        shopcart.setOnClickListener(this);
        titleFilter.setOnClickListener(this);

        product_name = (TextView)findViewById(R.id.product_name);
        LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) product_name.getLayoutParams();
        lp.topMargin = getScreenWidth(mContext);

        product_price = (TextView)findViewById(R.id.product_price);
        product_mktprice = (TextView)findViewById(R.id.product_mktprice);
        product_totalsaved = (TextView)findViewById(R.id.product_totalsaved);
        product_wight = (TextView)findViewById(R.id.product_wight);
        product_brand = (TextView)findViewById(R.id.product_brand);
        product_sort = (TextView)findViewById(R.id.product_sort);
        product_number = (TextView)findViewById(R.id.product_number);
        product_guigetxt = (TextView)findViewById(R.id.product_guigetxt);
        product_save = (ImageView)findViewById(R.id.product_save);
        product_save.setOnClickListener(this);
        product_share = (ImageView)findViewById(R.id.product_share);
        product_share.setOnClickListener(this);
        product_addtoshoppingcart = (TextView)findViewById(R.id.product_addtoshoppingcart);
        product_buynow = (TextView)findViewById(R.id.product_buynow);
        product_fast_buynow = (TextView)findViewById(R.id.product_fast_buynow);
        product_addtoshoppingcart.setOnClickListener(this);
        product_buynow.setOnClickListener(this);
        product_fast_buynow.setOnClickListener(this);
        product_empty = (TextView)findViewById(R.id.product_empty);
        product_bottom_lay = (LinearLayout)findViewById(R.id.product_bottom_lay);
        product_timetxt = (TextView)findViewById(R.id.product_timetxt);
        product_timerview = (CustomDigitalClock)findViewById(R.id.product_timerview);
        product_timerlay = (LinearLayout)findViewById(R.id.product_timerlay);
        product_endtag = (TextView)findViewById(R.id.product_endtag);

        product_guige_lay = (LinearLayout)findViewById(R.id.product_guige_lay);
        product_guige_lay.setOnClickListener(this);
        scrollview = (MyParallaxScrollView)findViewById(R.id.scrollview);
        web = (WebView)findViewById(R.id.product_webview);

        //		scrollview.setBackgroundDrawableId(strs);
        //		m.setForegroundDrawable(new ColorDrawable(R.color.transparent));  //设置前景
        scrollview.setDiffFactor(0.3f);

        if(secondId!=null && !secondId.equals("")){   //秒杀 专享
            product_buynow.setVisibility(View.GONE);
            product_addtoshoppingcart.setVisibility(View.GONE);
            product_fast_buynow.setVisibility(View.VISIBLE);
        }else{
            product_buynow.setVisibility(View.VISIBLE);
            product_addtoshoppingcart.setVisibility(View.VISIBLE);
            product_fast_buynow.setVisibility(View.GONE);
        }


        initPopWindow();

        getDetialData();
    }

    private void initPopWindow(){
        View v = LayoutInflater.from(mContext).inflate(R.layout.productdetial_more, null);
        v.findViewById(R.id.shareTxt).setOnClickListener(ProductDetialActivity.this);
        v.findViewById(R.id.firstpageTxt).setOnClickListener(this);
        int screenWidth = getScreenWidth(this);
        pop = new PopupWindow(v,screenWidth*2/5, FlowLayout.LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setOutsideTouchable(true);
        pop.setAnimationStyle(R.style.Animations_PopDownMenu_Right);
        pop.update();
        pop.setTouchable(true);
        pop.setFocusable(true);
    }

    private void getDetialData(){
        showLoadingDialog();
        GoodsGetRequest getDetialReq = new GoodsGetRequest() {
            @Override
            public String giveProductId() {
                return productId==null?"":productId;
            }

            @Override
            public String giveType() {
                return type==null?"0":type;
            }

            @Override
            public String giveRelativeId() {
                return relativeId==null?"":relativeId;
            }

            @Override
            public String giveDeviceId() {
                return deviceId==null?"":deviceId;
            }
        };

        RemoteServiceFactory.getInstance().getGoodsService(this).get(getDetialReq, new RemoteServiceListenerT<GoodsGetResponse>() {
            @Override
            public void okData(GoodsGetResponse goodsGetResponse) {
                super.okData(goodsGetResponse);
                dismissLoadingDialog();
                tt = goodsGetResponse;
                L.d("hp", "ProductDetialActivity GoodsGetResponse:" + goodsGetResponse.getName());
                //初始化分享数据
                shareParams = new Platform.ShareParams();
                shareParams.setShareType(Platform.SHARE_TEXT);
                shareParams.setShareType(Platform.SHARE_WEBPAGE);
                if (!TextUtils.isEmpty(goodsGetResponse.getName()))
                    shareParams.setTitle(goodsGetResponse.getName());
                if (!TextUtils.isEmpty(goodsGetResponse.getBrief()))
                    shareParams.setText(goodsGetResponse.getBrief());
                if (goodsGetResponse.getPics().size() > 0)
                    shareParams.setImageUrl(goodsGetResponse.getPics().get(0));
                refreshUI(goodsGetResponse);
            }

            @Override
            public void failue(int errorNo, String strMsg) {
                super.failue(errorNo, strMsg);
                if (errorNo == 0) { // 无商品
                    product_empty.setVisibility(View.VISIBLE);
                    product_bottom_lay.setVisibility(View.GONE);
                    scrollview.setVisibility(View.GONE);
                }
                dismissLoadingDialog();
            }
        });
    }

    private void refreshUI(GoodsGetResponse t){

        if(secondId!=null && !secondId.equals("") && isFastBuy.equals("2")){   //秒杀2 专享4 ？
            product_timerlay.setVisibility(View.VISIBLE);
            product_endtag.setVisibility(View.GONE);

            if(type!=null && type.equals("2")){    //秒杀
                if(isMiaosha!=null && isMiaosha.equals("0")){  //未开抢  显示几点开抢
                    //secondsMode   product_timetxt  product_timerview  product_timerlay   product_endtag
                    product_endtag.setVisibility(View.GONE);
                    product_timerview.setVisibility(View.GONE);
                    if(secondsMode1!=null){
                        product_timetxt.setText(""+ AppInforUtil.transferLongToDate("HH:mm", (Long.parseLong(secondsMode1.getBeginTime())) * 1000)+"准时开抢");
                    }else if(secondsMode2!=null){
                        product_timetxt.setText(""+AppInforUtil.transferLongToDate("HH:mm",(Long.parseLong(secondsMode2.getBeginTime())) * 1000)+"准时开抢");
                    }

//					product_fast_buynow.setBackgroundColor(getResources().getColor(R.color.gry_font));
//					product_fast_buynow.setEnabled(false);
//					if(notice.equals("1")){   //已经开启了提醒
                    if(tt.getIsNoticed().equals("1")){
                        product_fast_buynow.setBackgroundColor(getResources().getColor(R.color.pink_deep));
                        product_fast_buynow.setText("取消提醒");
                    }else{   //未开启提醒
                        product_fast_buynow.setBackgroundColor(getResources().getColor(R.color.pink_font));
                        product_fast_buynow.setText("开启提醒");
                    }
                    product_fast_buynow.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
//							if(notice.equals("1")){

                            if(SharedPreferenceUtils.getValueByKey(ProductDetialActivity.this, "memberId").equals("")){
                                Toast.makeText(ProductDetialActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                                Intent intent1 = new Intent(ProductDetialActivity.this, LoginActivity.class);
                                intent1.putExtra("type", "1");
                                startActivity(intent1);
                            }else{
                                if(tt.getIsNoticed().equals("1")){
                                    product_fast_buynow.setBackgroundColor(getResources().getColor(R.color.pink_font));
                                    product_fast_buynow.setText("开启提醒");
                                    if(isFirstOne!=null && isFirstOne.equals("1")){

                                    }
//                                        EventBus.getDefault().post(new NoticeEvent("0"));
//                                    notice("0");
                                }else{
                                    product_fast_buynow.setBackgroundColor(getResources().getColor(R.color.pink_deep));
                                    product_fast_buynow.setText("取消提醒");
                                    if(isFirstOne!=null && isFirstOne.equals("1")){

                                    }
//                                        EventBus.getDefault().post(new NoticeEvent("1"));
//                                    notice("1");
                                }

                            }

                        }
                    });

                }else if(isMiaosha!=null && isMiaosha.equals("1")){  //已开抢  显示倒计时
                    product_endtag.setVisibility(View.GONE);
                    product_timerview.setVisibility(View.VISIBLE);
                    product_timetxt.setText(" 后结束");
                    if(secondsMode1!=null){
                        product_timerview.setTimeGap(timeGap);

                        product_timerview.setEndTime(Long.parseLong(secondsMode1.getEndTime())*1000);
                    }else if(secondsMode2!=null){
                        product_timerview.setTimeGap(timeGap);
                        product_timerview.setEndTime(Long.parseLong(secondsMode2.getEndTime())*1000);
                    }
                    product_timerview.setClockListener(new CustomDigitalClock.ClockListener() {

                        @Override
                        public void timeEnd() {
//                            RbLog.i("倒计时到点");
                            getDetialData();
                        }

                        @Override
                        public void remainFiveMinutes() {
                        }
                    });

                    if(t.getQuantity().equals("0")){   //库存为0
                        product_fast_buynow.setText("已售罄");
                        product_fast_buynow.setBackgroundColor(getResources().getColor(R.color.gry_font));
                        product_fast_buynow.setEnabled(false);
                        //已结束 显示 已结束 标签
                        product_timerlay.setVisibility(View.GONE);
                        product_endtag.setVisibility(View.VISIBLE);
                    }
                    product_fast_buynow.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            if(SharedPreferenceUtils.getValueByKey(mContext, "memberId").equals("")){
                                Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
                                Intent intent1 = new Intent(mContext, LoginActivity.class);
                                intent1.putExtra("type", "1");
                                startActivity(intent1);
                            }else{

                                if(tt.getSpecs().size()>0 && isMultiTag){    //有标签时候才弹出详情框
                                    popwindow = new ProductSpecificationPopwindow(mContext, tt ,isFastBuy);
                                    if(!popwindow.isShowing()){
                                        popwindow.show();
                                        popwindow.setOnActionSheetItemClickedListener(new ProductSpecificationPopwindow.ActionSheetItemClickedListener() {

                                            @Override
                                            public void OnTagClicked(GoodsGetPriceResponse t,String tagtxt) {  // 标签
                                                priceChanged(t,tagtxt);
                                            }

                                            @Override
                                            public void OnSubmit() {      //提交
                                                pluslayCount = 1;
                                                isBuyNow = true;
//                                                CommonUtils.refreshShopCart = true;
//                                                add2ShopCart();

                                            }

                                            @Override
                                            public void OnCountChanged(int n) {      //计数器
                                                pluslayCount = n;
                                            }
                                        });
                                    }
                                }else{
                                    pluslayCount = 1;
                                    add2ShopCart();

                                    isBuyNow = true;
//                                    CommonUtils.refreshShopCart = true;
                                }

                            }
                        }
                    });
                }
            }

        }else if(secondId!=null && !secondId.equals("") && isFastBuy.equals("4")){   //新人专享
            product_fast_buynow.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
//                    RbLog.i("新人专享 product_fast_buynow");
                    if(SharedPreferenceUtils.getValueByKey(mContext, "memberId").equals("")){
                        Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
                        Intent intent1 = new Intent(mContext, LoginActivity.class);
                        intent1.putExtra("type", "1");
                        startActivity(intent1);
                    }

//                    else{
                        //检查是否是新人购买
//                        RemoteServiceFactory.getInstance().getAccountService(mContext).checkIsNewUser(new AccountCheckNewUserRequest(), new RemoteServiceListener<AccountCheckIsNewUserResponse>() {
//
//                            @Override
//                            public void ok(AccountCheckIsNewUserResponse t) {
//                                RbLog.i("t.isNewUser()="+t.isNewUser());
//                                if(t.isNewUser()){   //是新人
//                                    if(tt.getSpecs().size()>0 && isMultiTag){    //有标签时候才弹出详情框
//                                        popwindow = new ProductSpecificationPopwindow(mContext, tt ,isFastBuy);
//                                        if(!popwindow.isShowing()){
//                                            popwindow.show();
//                                            popwindow.setOnActionSheetItemClickedListener(new ActionSheetItemClickedListener() {
//
//                                                @Override
//                                                public void OnTagClicked(GoodsGetPriceResponse t,String tagtxt) {  // 标签
//                                                    priceChanged(t,tagtxt);
//                                                }
//
//                                                @Override
//                                                public void OnSubmit() {      //提交
//                                                    pluslayCount = 1;
//                                                    isBuyNow = true;
//                                                    CommonUtils.refreshShopCart = true;
//                                                    add2ShopCart();
//
//                                                }
//
//                                                @Override
//                                                public void OnCountChanged(int n) {      //计数器
//                                                    pluslayCount = n;
//                                                }
//                                            });
//                                        }
//                                    }else{
//                                        pluslayCount = 1;
//                                        add2ShopCart();
//
//                                        isBuyNow = true;
//                                        CommonUtils.refreshShopCart = true;
//                                    }
//                                }else{   //提示 该商品为新用户专享
//                                    BaseDialog.showCouponsTipsDialog(mContext, "", "该商品为新用户专享，您目前身份不是新用户，将无法购买", null);
//
//                                }
//                            }
//
//                            @Override
//                            public void failue(int errorCode, String errorMessage) {
//
//                            }
//                        });
//
//                    }
                }
            });
        }else{    //普通商品
            //隐藏timer标签
            product_timerlay.setVisibility(View.GONE);
            product_endtag.setVisibility(View.GONE);

            if(t.getQuantity().equals("0")){   //库存为0
                product_buynow.setVisibility(View.GONE);
                product_addtoshoppingcart.setVisibility(View.GONE);
                product_fast_buynow.setVisibility(View.VISIBLE);

                product_fast_buynow.setText("已售罄");
                product_fast_buynow.setBackgroundColor(getResources().getColor(R.color.gry_font));
                product_fast_buynow.setEnabled(false);
            }
        }

        goodsId = t.getGoodsId();
        scrollview.setBackgroundDrawableId(t.getPics());  // banner
        scrollview.setCountryInfo(t.getCountryImg(), t.getCountryName(), t.getDiscount());

        if(!TextUtils.isEmpty(t.getName())){
            if(secondId!=null && !secondId.equals("") && (isFastBuy.equals("2"))){  //秒杀的话名称前带  秒杀  标签
                CharSequence name = "★ "+t.getName();
                SpannableStringBuilder builder = new SpannableStringBuilder(name);
                String rexgString = "★";
                Pattern pattern = Pattern.compile(rexgString);
                Matcher matcher = pattern.matcher(name);

                while (matcher.find()) {
                    builder.setSpan(new ImageSpan(this, R.drawable.tag_panicbuying), matcher.start(),
                            matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }

                product_name.setText(builder);
            }else if(secondId!=null && !secondId.equals("") && (isFastBuy.equals("4"))){  //新人专享 带标签
                CharSequence name = "★ "+t.getName();
                SpannableStringBuilder builder = new SpannableStringBuilder(name);
                String rexgString = "★";
                Pattern pattern = Pattern.compile(rexgString);
                Matcher matcher = pattern.matcher(name);

                while (matcher.find()) {
                    builder.setSpan(new ImageSpan(this, R.drawable.tips_special), matcher.start(),
                            matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }

                product_name.setText(builder);
            }else{
                product_name.setText(t.getName());  //商品名称
            }

        }

        String s = "";
        if(!TextUtils.isEmpty(t.getPrice())){
            s = "￥"+AppInforUtil.formatPrice3(t.getPrice());
        }
        Spannable WordtoSpan = new SpannableString(s);
        WordtoSpan.setSpan(new AbsoluteSizeSpan(DensityUtils.dip2px(this, 11)), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        WordtoSpan.setSpan(new AbsoluteSizeSpan(DensityUtils.dip2px(this, 16)), 1, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        product_price.setText(WordtoSpan);

        String mktprice = "0";
        if(!TextUtils.isEmpty(t.getMktprice())){
            mktprice = AppInforUtil.formatPrice3(t.getMktprice());
        }
        SpannableString sp = new SpannableString("￥" + mktprice);
        sp.setSpan(new StrikethroughSpan(), 0, mktprice.length()+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        product_mktprice.setText(sp);

        if(!TextUtils.isEmpty(t.getMktprice()) && !TextUtils.isEmpty(t.getPrice()))
            product_totalsaved.setText("为你节省￥"+ AppInforUtil.formatPrice3(Double.parseDouble(t.getMktprice())- Double.parseDouble(t.getPrice())));

        if(!TextUtils.isEmpty(t.getWeight()))
            product_wight.setText("重量：" + AppInforUtil.formatPrice3(t.getWeight())+ "g");

        product_brand.setText(t.getBrandName());
        product_sort.setText(t.getCatName());
        product_number.setText(t.getBn());

        for(GoodsGetSpecs ggs:tt.getSpecs()){
            if(ggs.getSpecValues().size()>1){
                isMultiTag = true;
            }
        }

        if(t.getSpecs().size()>0){
            StringBuffer sb = new StringBuffer();
            for(GoodsGetSpecs ggs:t.getSpecs()){
                for(GoodsGetSpecsSpecValues ggss:ggs.getSpecValues()){
                    if(t.getProductId().equals(""+ggss.getProductId())){
                        sb.append(ggss.getSpecValue()+" ");
                    }
                }
            }
            product_guigetxt.setText(sb.toString());
        }

        setWebView(AppInforUtil.loadWebView(t.getIntro()));

        if (t.getIsFaved().equals("0")) {
            // 未收藏
            product_save.setImageResource(R.drawable.notselectcollection);
            savedTag = 0;
        } else {
            // 已收藏
            product_save.setImageResource(R.drawable.selectcollection);
            savedTag = 1;
        }

    }

    private void setWebView(String url){

        web.loadData(url, "text/html", "utf-8");
        WebSettings webSettings = web.getSettings();

        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        web.setVerticalScrollBarEnabled(false);
        web.setVerticalScrollbarOverlay(false);
        web.setHorizontalScrollBarEnabled(false);
        web.setHorizontalScrollbarOverlay(false);

        web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        web.removeJavascriptInterface("searchBoxJavaBredge_");

    }

    @Override
    protected void onResume() {
        super.onResume();
        pluslayCount = 1;
//		getStatus();
        getStaticsInfo(1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId()){

            case R.id.product_addtoshoppingcart:   //普通商品 加入购物车

                if(SharedPreferenceUtils.getValueByKey(mContext, "memberId").equals("")){
                    Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    intent.putExtra("type", "1");
                    startActivity(intent);
                }else{
                    boolean selecteable = false;
                    a:
                    for(GoodsGetSpecs ggs:tt.getSpecs()){
                        if(ggs.getSpecValues().size()>1){
                            selecteable = true;
                            break a;
                        }
                    }

                    if(selecteable){  //有规格 并且有可选择性
                        popwindow = new ProductSpecificationPopwindow(mContext, tt ,isFastBuy);
                        if(!popwindow.isShowing()){
                            popwindow.show();
                            popwindow.setOnActionSheetItemClickedListener(new ProductSpecificationPopwindow.ActionSheetItemClickedListener() {

                                @Override
                                public void OnTagClicked(GoodsGetPriceResponse t,String tagtxt) {  // 标签
                                    priceChanged(t,tagtxt);
                                }

                                @Override
                                public void OnSubmit() {      //提交

                                    reclassify_addcartiv.setVisibility(View.VISIBLE);
                                    if(tt.getPics().size()>0)
                                        RbImageLoader.displayImage(tt.getPics().get(0), DensityUtils.dip2px(mContext, 20), reclassify_addcartiv);
                                    reclassify_addcartiv.startAnimation(animation2);

                                    if(!isAniting){
                                        new Handler().postDelayed(new Runnable() {

                                            @Override
                                            public void run() {
                                                startAnim();
                                            }
                                        }, 1000);
                                    }
                                    isBuyNow = false;
                                    isAdd2Shopcart = true;   //添加到购物车
//                                    add2ShopCart();
                                }

                                @Override
                                public void OnCountChanged(int n) {      //计数器
                                    pluslayCount = n;
                                }
                            });
                        }

                    }else{   //没有规格

                        reclassify_addcartiv.setVisibility(View.VISIBLE);
                        if(tt.getPics().size()>0)
                            RbImageLoader.displayImage(tt.getPics().get(0), DensityUtils.dip2px(mContext, 20), reclassify_addcartiv);
                        reclassify_addcartiv.startAnimation(animation2);

                        if(!isAniting){
                            new Handler().postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    startAnim();
                                }
                            }, 1000);
                        }
                        isBuyNow = false;
                        isAdd2Shopcart = true;   //添加到购物车
//                        add2ShopCart();
                    }
                }

                break;
            case R.id.product_buynow:    //普通商品立即购买
                if(SharedPreferenceUtils.getValueByKey(mContext, "memberId").equals("")){
                    Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    intent.putExtra("type", "1");
                    startActivity(intent);
                }else{

                    boolean selecteable = false;
                    a:
                    for(GoodsGetSpecs ggs:tt.getSpecs()){
                        if(ggs.getSpecValues().size()>1){
                            selecteable = true;
                            break a;
                        }
                    }

                    if(selecteable){  //有规格 并且有可选择性
                        //有规格 并且有可选择性
                        popwindow = new ProductSpecificationPopwindow(mContext, tt ,isFastBuy);
                        if(!popwindow.isShowing()){
                            popwindow.show();
                            popwindow.setOnActionSheetItemClickedListener(new ProductSpecificationPopwindow.ActionSheetItemClickedListener() {

                                @Override
                                public void OnTagClicked(GoodsGetPriceResponse t,String tagtxt) {  // 标签
                                    priceChanged(t,tagtxt);
                                }

                                @Override
                                public void OnSubmit() {      //提交
                                    if(!isAniting){
                                        startAnim();
                                    }
                                    isBuyNow = false;
                                    isAdd2Shopcart = false;   //立即购买
//                                    add2ShopCart();
                                }

                                @Override
                                public void OnCountChanged(int n) {      //计数器
                                    pluslayCount = n;
                                }
                            });
                        }

                    }else{   //没有规格
                        isBuyNow = false;
                        isAdd2Shopcart = false;   //立即购买
//                        add2ShopCart();
                    }
                }
                break;
            case R.id.product_fast_buynow:   //秒杀立即购买
                if(SharedPreferenceUtils.getValueByKey(mContext, "memberId").equals("")){
                    Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
                    Intent intent1 = new Intent(mContext, LoginActivity.class);
                    intent1.putExtra("type", "1");
                    startActivity(intent1);
                }else{

                    if(tt.getSpecs().size()>0 && isMultiTag){    //有标签时候才弹出详情框
                        popwindow = new ProductSpecificationPopwindow(mContext, tt ,isFastBuy);
                        if(!popwindow.isShowing()){
                            popwindow.show();
                            popwindow.setOnActionSheetItemClickedListener(new ProductSpecificationPopwindow.ActionSheetItemClickedListener() {

                                @Override
                                public void OnTagClicked(GoodsGetPriceResponse t,String tagtxt) {  // 标签
                                    priceChanged(t,tagtxt);
                                }

                                @Override
                                public void OnSubmit() {      //提交
                                    pluslayCount = 1;
                                    isBuyNow = true;
//                                    CommonUtils.refreshShopCart = true;
                                    add2ShopCart();

                                }

                                @Override
                                public void OnCountChanged(int n) {      //计数器
                                    pluslayCount = n;
                                }
                            });
                        }
                    }else{
                        pluslayCount = 1;
                        add2ShopCart();
                        isBuyNow = true;
//                        CommonUtils.refreshShopCart = true;
                    }

                }
                break;
            case R.id.product_guige_lay://            请选择规格
                pluslayCount = 1;
                popwindow = new ProductSpecificationPopwindow(mContext, tt ,isFastBuy);
                if(!popwindow.isShowing()){
                    popwindow.show();
                    popwindow.setOnActionSheetItemClickedListener(new ProductSpecificationPopwindow.ActionSheetItemClickedListener() {

                        @Override
                        public void OnTagClicked(GoodsGetPriceResponse t,String tagtxt) {  // 标签
                            priceChanged(t,tagtxt);
                        }

                        @Override
                        public void OnSubmit() {      //提交
                            //					pluslayCount = 1;
                        }

                        @Override
                        public void OnCountChanged(int n) {      //计数器
                            pluslayCount = n;
                        }
                    });
                }
                break;

            case R.id.shopcart: // 右上 购物车
                if(SharedPreferenceUtils.getValueByKey(mContext, "memberId").equals("") || SharedPreferenceUtils.getValueByKey(mContext, "memberId").isEmpty()){
                    Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    intent.putExtra("type", "1");
                    startActivity(intent);
                }else{
//				startActivity(new Intent(this, ShoppingCartActivity.class));
                    Intent intent = new Intent(this, MainActivity.class);
                    intent.putExtra("TURNBACKFIRST", "5");
                    startActivity(intent);
                }
                break;
            case R.id.filterImg: // 右上 分享
                if(pop.isShowing()){
                    pop.dismiss();
                }else{
                    pop.showAsDropDown(v,0,0);
                }
                break;
            case R.id.shareTxt:   //联系客服
                if(pop.isShowing())
                    pop.dismiss();
//                showTipsDialog();
                break;
            case R.id.firstpageTxt: //首页
                Intent intent = new Intent(this, MainActivity.class);
                intent.putExtra("TURNBACKFIRST", "4");
                startActivity(intent);
                pop.dismiss();
                break;
            case R.id.product_save:  //收藏
                if(SharedPreferenceUtils.getValueByKey(mContext, "memberId").equals("")){
                    Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
                    Intent saveintent = new Intent(mContext, LoginActivity.class);
                    saveintent.putExtra("type", "1");
                    startActivity(saveintent);
                }else{
                    saveGoods(savedTag);
                }
                break;
            case R.id.product_share:   //分享
                pop.dismiss();
                showSharePlane();
                break;
            case R.id.weichat_butt:   //微信分享

                CommonShareGoodsRequest shareReq = new CommonShareGoodsRequest() {
                    @Override
                    public String giveProdctId() {
                        return productId;
                    }
                };
                RemoteServiceFactory.getInstance().getCommonService(this).shareGoods(shareReq, new RemoteServiceListenerT<CommonShareGoodsResponse>() {
                    @Override
                    public void okData(CommonShareGoodsResponse commonShareGoodsResponse) {
                        super.okData(commonShareGoodsResponse);
                        shareParams.setUrl(commonShareGoodsResponse.getUrl());
                        share(shareParams, "Wechat");
                    }
                });
                dialog.dismiss();
                break;
            case R.id.moment_butt:   //朋友圈分享

                CommonShareGoodsRequest shareReq1 = new CommonShareGoodsRequest() {
                    @Override
                    public String giveProdctId() {
                        return productId;
                    }
                };
                RemoteServiceFactory.getInstance().getCommonService(this).shareGoods(shareReq1, new RemoteServiceListenerT<CommonShareGoodsResponse>() {
                    @Override
                    public void okData(CommonShareGoodsResponse commonShareGoodsResponse) {
                        super.okData(commonShareGoodsResponse);
                        shareParams.setUrl(commonShareGoodsResponse.getUrl());
                        share(shareParams,"WechatMoments");
                    }
                });
                dialog.dismiss();
                dialog.dismiss();
                break;
            //		case R.id.sina_butt:  //新浪分享
            //			GoodsGetShareUrlRequest r = new GoodsGetShareUrlRequest();
            //			r.setProdctId(productId);
            //			r.setRudder_position(IntegrateConst.DETAIL_SHARE);
            //			r.setRudder_route(IntegrateConst.OTHER_ROUTE);
            //			RemoteServiceFactory.getInstance().getGoodsService(mContext).getShareUrl(r, new RemoteServiceListener<GoodsGetShareUrlResponse>() {
            //
            //				@Override
            //				public void ok(GoodsGetShareUrlResponse t) {
            //					RbLog.i("url===="+t.getUrl());
            //					shareParams.setUrl(t.getUrl());
            //
            //					share(shareParams,"SinaWeibo");
            //				}
            //
            //				@Override
            //				public void failue(int errorCode, String errorMessage) {
            //					RbLog.i("errorMessage===="+errorMessage);
            //				}
            //			});
            //
            //			dialog.dismiss();
            //			break;
            //		case R.id.qzone_butt:  //qq空间分享
            //			GoodsGetShareUrlRequest qzone = new GoodsGetShareUrlRequest();
            //			qzone.setProdctId(productId);
            //			qzone.setRudder_position(IntegrateConst.DETAIL_SHARE);
            //			qzone.setRudder_route(IntegrateConst.OTHER_ROUTE);
            //			RemoteServiceFactory.getInstance().getGoodsService(mContext).getShareUrl(qzone, new RemoteServiceListener<GoodsGetShareUrlResponse>() {
            //
            //				@Override
            //				public void ok(GoodsGetShareUrlResponse t) {
            //					RbLog.i("url===="+t.getUrl());
            //					shareParams.setUrl(t.getUrl());
            //					qzone(shareParams);
            //				}
            //
            //				@Override
            //				public void failue(int errorCode, String errorMessage) {
            //					RbLog.i("errorMessage===="+errorMessage);
            //				}
            //			});
            ////			qzone(shareParams);
            //			dialog.dismiss();
            //			break;
            //		case R.id.copy_butt:  //复制链接
            //			//TODO
            //			break;
            case R.id.share_cancle:
                dialog.dismiss();
                break;

        }
    }
    private void add2ShopCart(){

        ShoppingAddRequest addReq = new ShoppingAddRequest() {
            @Override
            public String giveProductId() {
                return productId==null?"":productId;
            }

            @Override
            public String giveIsFastBuy() {
                return isFastBuy==null?"0":isFastBuy;
            }

            @Override
            public String giveQuantity() {
                return ""+pluslayCount;
            }

            @Override
            public String giveTargetId() {
                return secondId==null?"":secondId;
            }

            @Override
            public String giveRudderRoute() {
                return "";
            }
        };
        RemoteServiceFactory.getInstance().getShoppingService(this).add(addReq, new RemoteServiceListenerT<ShoppingAddResponse>() {
            @Override
            public void okData(ShoppingAddResponse shoppingAddResponse) {
                super.okData(shoppingAddResponse);

            }
        });
    }


    private void priceChanged(GoodsGetPriceResponse t,String tagtxt){
        productId = t.getProductId();

        product_guigetxt.setText(tagtxt);
        String s = "";
        if(!TextUtils.isEmpty(t.getPrice())){
            s = "￥"+AppInforUtil.formatPrice3(t.getPrice());
        }
        Spannable WordtoSpan = new SpannableString(s);
        WordtoSpan.setSpan(new AbsoluteSizeSpan(DensityUtils.dip2px(ProductDetialActivity.this, 11)), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        WordtoSpan.setSpan(new AbsoluteSizeSpan(DensityUtils.dip2px(ProductDetialActivity.this, 16)), 1, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        product_price.setText(WordtoSpan);

        String mktprice = "0";
        if(!TextUtils.isEmpty(t.getMktprice())){
            mktprice = AppInforUtil.formatPrice3(t.getMktprice());
        }
        SpannableString sp = new SpannableString("￥" + mktprice);
        sp.setSpan(new StrikethroughSpan(), 0, mktprice.length()+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        product_mktprice.setText(sp);

        if(!TextUtils.isEmpty(t.getMktprice()) && !TextUtils.isEmpty(t.getPrice()))
            product_totalsaved.setText("为你节省￥"+ AppInforUtil.formatPrice3(Double.parseDouble(t.getMktprice())- Double.parseDouble(t.getPrice())));

    }

    private void startAnim(){
        b = 0;
        shopcart.animate().translationYBy(-dip2px(mContext, 10)).setDuration(300).setInterpolator(new AccelerateInterpolator()).setListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator arg0) {
                b++;isAniting = true;
            }
            @Override
            public void onAnimationRepeat(Animator arg0) {}
            @Override
            public void onAnimationEnd(Animator arg0) {
                isAniting = false;
                if(b==1) shopcart.animate().translationYBy(dip2px(mContext, 10)).setDuration(500).setInterpolator(new BounceInterpolator());
            }
            @Override
            public void onAnimationCancel(Animator arg0) {}
        });
    }

    private void showSharePlane(){
        if(dialog== null)
            dialog = new AlertDialog.Builder(this).create();
        dialog.show();
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth());
        dialog.getWindow().setAttributes(lp);
        dialog.getWindow().setWindowAnimations(R.style.AnimUp);
        View v = LayoutInflater.from(this).inflate(R.layout.dialog_share2, null);
        LinearLayout share2_lay1 = (LinearLayout) v.findViewById(R.id.share2_lay1);
        TextView share_cancle = (TextView) v.findViewById(R.id.share_cancle);
        share_cancle.getBackground().setAlpha(230);
        share2_lay1.getBackground().setAlpha(230);
        RelativeLayout relay = (RelativeLayout)v.findViewById(R.id.sharedialog_rellay);
        relay.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent arg1) {
                dialog.dismiss();
                return false;
            }
        });

        v.findViewById(R.id.weichat_butt).setOnClickListener(this);
        v.findViewById(R.id.moment_butt).setOnClickListener(this);
        //		v.findViewById(R.id.sina_butt).setOnClickListener(this);
        //		v.findViewById(R.id.qzone_butt).setOnClickListener(this);
        //		v.findViewById(R.id.copy_butt).setOnClickListener(this);
        v.findViewById(R.id.share_cancle).setOnClickListener(this);
        dialog.getWindow().setContentView(v);
        //		dialog.getWindow().findViewById(R.id.cancel);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
    }

    private void saveGoods(final int savedTag){
        GoodsFavoriteRequest favoriteReq = new GoodsFavoriteRequest() {
            @Override
            public String giveGoodsId() {
                return goodsId==null?"":goodsId;
            }

            @Override
            public String giveStatus() {
                return ""+savedTag;
            }
        };
        RemoteServiceFactory.getInstance().getGoodsService(this).favorite(favoriteReq, new RemoteServiceListenerT<GoodsFavoriteResponse>() {
            @Override
            public void okData(GoodsFavoriteResponse goodsFavoriteResponse) {
                super.okData(goodsFavoriteResponse);
                if (product_save.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(
                        R.drawable.selectcollection).getConstantState())) { // 未收藏
                    product_save.setImageResource(R.drawable.notselectcollection);
                    Toast.makeText(mContext, "取消收藏成功", Toast.LENGTH_SHORT).show();
                } else { // 已收藏
                    Toast.makeText(mContext, "收藏成功", Toast.LENGTH_SHORT).show();
                    product_save.setImageResource(R.drawable.selectcollection);
                }
            }
        });
    }

    private void share(Platform.ShareParams shareParams,String platform){
        Platform plat = null;
        plat = ShareSDK.getPlatform(this, platform);
        plat.setPlatformActionListener(null);
        plat.share(shareParams);
    }
}
